'use strict';
let http = require("http");  
let key = '8292b4d51f3900b8f44d8810c7231c3c';
// let place = encoding.convert("北京", "utf8");
let urllocal = 'http://api.openweathermap.org/data/2.5/forecast';

var wf = require('../model/weather_forcast');


//暴漏定义的模块方法
exports.getFoUrl = getFoUrl;
function getFoUrl(place,mode) {
  let url = urllocal+'?q='+'\''+place+'\''+'&mode='+mode+'&appid='+key;
  return url;
} 

exports.getFWeather = getFWeather;
function getFWeather(citylist,flag) {
	let obj1 = {};
	/*console.log('-----------------新数据data----------------');*/
	//console.log('this.getUrl()---------',citylist);
	var len = citylist.length;
	console.log('=---citylist[i].pinYin-----',citylist);
	for(var i=0;i<len;i++){
		var place = citylist[i].pinYin;
		
		var url = getFoUrl(place,'json');
		console.log('=---折有问题---------------'+url+'----------------------'+place);
		let req = http.get(url, function(res) {
			let data = '';
			res.on('data', function(d) {
			  data += d;
			  var aa = process.stdout.write(d);
			});
			res.on('end',function(){
				//把数据保存到数据库
				var obj1 = JSON.parse(data);
				//console.log('---------------折有问题----------',data);
				var list = trandata(obj1);
				console.log('---------------flag----------',flag);
				if(flag==0){
					wf.saveWeatherForcast(list);
				}
				else{
					wf.updateWeatherForcast(list);
				}
				/**/
			
			});
			res.on('error', function(e) {
			  console.error(e);
		    });
		});
	}
}

function trandata(obj1){
	var weatherlsit = [];
	var cityname = obj1.city.name;
	//console.log("name----------------------------",obj1.city);
	var citylist = [];
	citylist = obj1.list;
	var len = citylist.length;
	for(var i=0;i<len;i++){
		var wobj = createWeatherObj(citylist[i],cityname);
		/*console.log('---wobj-----',wobj);*/
		weatherlsit.push(wobj);
	}
	/*console.log('---weatherlsit-----',weatherlsit);*/
	return weatherlsit;

}

function createWeatherObj(obj,name){
	var wea = {};
	wea.cityName=name;//城市名称
	wea.humidity = obj.main.humidity;//湿度
	wea.pressure = obj.main.pressure;//大气压
	wea.clouds = obj.clouds.all;//云
	wea.temp = obj.main.temp;
	wea.temp_min = obj.main.temp_min;//最小温度
	wea.temp_max = obj.main.temp_max;//最小温度
	wea.icon = obj.weather[0].icon;
	wea.description = obj.weather[0].description;
	wea.weather_main = obj.weather[0].main;
	wea.temp_kf = obj.main.temp_kf;
	wea.sea_level = obj.main.sea_level;
	wea.grnd_level = obj.main.grnd_level;
	wea.wind_speed = obj.wind.speed;
	wea.wind_deg = obj.wind.deg;
	wea.weatherTime = obj.dt_txt;
	return wea;
}
